package cn.kent.middle;

/**
 * hot100 19.删除倒数第n个节点
 * 0ms
 */
public class RemoveNthFromEnd {
    public static void main(String[] args) {
        ListNode head = new ListNode(0);
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        head.next = n1;
        n1.next = n2;
        n2.next = n3;

        ListNode res = removeNthFromEnd(head, 2);
        System.out.println(res);
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        // 判断初始值
        if (n <= 0) return head;

        int len = 0;
        ListNode tmpHead = head;
        ListNode delPreNode = null;
        ListNode delNode = null;
        // 开始循环
        while (tmpHead != null) {
            if ((len + 1) - n == 0) {
                delNode = head;
            }
            if ((len + 1) - n == -1) {
                delPreNode = head;
            }
            if ((len + 1) - n >= 1) {
                delPreNode = delNode;
                delNode = delPreNode.next;
            }
            tmpHead = tmpHead.next;
            len++;
        }

        // 删除
        if (delNode == head) head = head.next;
        if (delPreNode != null) delPreNode.next = delNode.next;

        return head;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
